
/****** Object:  StoredProcedure [dbo].[ws_ins_voucher]    Script Date: 10/19/2013 09:22:25 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'ws_ins_voucher')
DROP PROCEDURE ws_ins_voucher
GO

CREATE PROCEDURE [dbo].[ws_ins_voucher] 
(		
	@aparato_id varchar(255), 
	@kortelesnr varchar(255), 
	@barkodas varchar(255), 
	@kiekis varchar(255), 
	@suma varchar(255),
	@pvm varchar(255)
)
AS
BEGIN
	DECLARE @zetas int
	DECLARE @nuo datetime
	DECLARE @iki datetime
	DECLARE @galvaid int
	DECLARE @data datetime
	DECLARE @kvitonr int
	DECLARE @KvNr int
	DECLARE @tmp varchar(11)
	DECLARE @mok numeric(12,2)
	
	If not exists(select * from zetai where ID = @aparato_id and CONVERT (date,current_timestamp) >= NUO and CONVERT (date,current_timestamp) <= IKI)
	begin
		SELECT @zetas = MAX(zetas) from zetai where ID = @aparato_id

		SET @zetas = isnull(@zetas,0) + 1

		if day(current_timestamp) < 16
		begin
			SET @nuo = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0) --1
			SET @iki = CAST(CAST(year(CURRENT_TIMESTAMP) as varchar) + '-' + cast(month(CURRENT_TIMESTAMP) as varchar) + '-' + '15 23:59:00'  AS DATETIME)
		end
		else	
		begin
			SET @nuo = CAST(cast(year(CURRENT_TIMESTAMP) as varchar) + '-' + cast(month(CURRENT_TIMESTAMP) as varchar) + '-' + '16 00:00:00'  AS DATETIME)
			SET @iki = DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, CURRENT_TIMESTAMP) + 1, 0))	--31
		end
		insert into zetai (ID,ZETAS,NUO,IKI,KADA) values (@aparato_id,@zetas,@nuo,@iki,CONVERT (date, @iki))		
	end
	else
		SELECT @zetas = max(zetas) from zetai where ID = @aparato_id and CONVERT (date,current_timestamp) >= NUO and CONVERT (date,current_timestamp) <= IKI

	BEGIN TRANSACTION
	    SELECT top 1 @tmp = SUBSTRING(kvitonr2,1,CHARINDEX('/', kvitonr2)-1) from kvitogalva where aparatoid = @aparato_id and znr = @zetas order by id desc
		
		
		if (@tmp is null)
			SET @KvNr = 1
		else
			SET @KvNr = CAST(@tmp as int) + 1
	    SET @data = current_timestamp
		SET @kvitonr = (@zetas*65536)+@KvNr
		
		insert into Kvitogalva  (aparatoid,kortelesnr,kvitonr,kvitonr2,data,import,year,month,day,hour,minute,znr,suma,apmokejimorusis) 
		values (@aparato_id,@kortelesnr,@kvitonr ,cast(@KvNr as varchar(10))+'/'+cast(@zetas as varchar(10)),@data,0,year(@data),month(@data),day(@data), DATEPART(hh, @data),DATEPART(mi,@data),@zetas,@suma,1)
		
		SET @galvaid  = SCOPE_IDENTITY()

		SET @mok = cast(@suma as numeric(12,2))-(cast(@suma as numeric(12,2))*100/(100+cast(@pvm as numeric(10,2)))) 
		
		insert into Kvitoeilute (barkodas,kiekis,galvosid,prekeskodas,suma,mokesciai ) 
		values (@barkodas,@kiekis,@galvaid,@barkodas,@suma,@mok)
		
	COMMIT TRANSACTION

END

GO

